package com.lu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lu.constants.BlogStatusConstants;
import com.lu.constants.HttpStatusEnum;
import com.lu.constants.UploadConstants;
import com.lu.dto.AjaxPutPage;
import com.lu.dto.AjaxResultPage;
import com.lu.dto.Result;
import com.lu.pojo.BlogInfo;
import com.lu.pojo.BlogLink;
import com.lu.pojo.BlogTagRelation;
import com.lu.service.BlogInfoService;
import com.lu.service.BlogTagRelationService;
import com.lu.utils.DateUtils;
import com.lu.utils.ResultGenerator;
import com.lu.utils.UploadFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 博客信息表 前端控制器
 * </p>
 *
 * @author xiaolu
 * @since 2020-05-31
 */
@Controller
@RequestMapping("/admin")
public class BlogInfoController {

    @Autowired
    private BlogInfoService blogInfoService;

    @Autowired
    private BlogTagRelationService blogTagRelationService;

    // 跳转到博客编辑页面
    @GetMapping("/v1/blog/edit")
    public String edit(@RequestParam(required = false) Long blogId, Model model){

        if (blogId != null){
            BlogInfo blogInfo = blogInfoService.getById(blogId);
            QueryWrapper<BlogTagRelation> queryWrapper = new QueryWrapper<>();
            // 查询列表
            List<BlogTagRelation> list = blogTagRelationService.list(
                    new QueryWrapper<BlogTagRelation>()
                            .lambda()
                            .eq(BlogTagRelation::getBlogId, blogId)
            );
            List<Integer> tags = null;
            if (!CollectionUtils.isEmpty(list)){
                tags = list.stream().map(
                        blogTagRelation -> blogTagRelation.getTagId())
                        .collect(Collectors.toList());
            }
            model.addAttribute("blogTags", tags);
            model.addAttribute("blogInfo", blogInfo);
        }
        return "admin/blog-edit";
    }

    // 保存文章图片
    @ResponseBody
    @PostMapping("/v1/blog/uploadFile")
    public Map<String,Object> uploadFileByEditormd(HttpServletRequest request,
                                                   @RequestParam(name = "editormd-image-file") MultipartFile file) throws URISyntaxException {
        String suffixName = UploadFileUtils.getSuffixName(file);
        //生成文件名称通用方法
        String newFileName = UploadFileUtils.getNewFileName(suffixName);
        File fileDirectory = new File(UploadConstants.FILE_UPLOAD_DIC);
        //创建文件
        File destFile = new File(UploadConstants.FILE_UPLOAD_DIC + newFileName);
        Map<String,Object> result = new HashMap<>();
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdirs()) {
                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
                }
            }
            file.transferTo(destFile);
            String fileUrl = UploadConstants.FILE_SQL_DIC + newFileName;
            result.put("success", 1);
            result.put("message","上传成功");
            result.put("url",fileUrl);
        } catch (IOException e) {
            result.put("success", 0);
        }
        return result;
    }

    // 保存文章内容
    @ResponseBody
    @PostMapping("/v1/blog/edit")
    public Result<String> edit(@RequestParam("blogTagIds[]") List<Integer> blogTagIds, BlogInfo blogInfo){

        // 如果博客和博客标签为空，返回400
        if (CollectionUtils.isEmpty(blogTagIds) || ObjectUtils.isEmpty(blogInfo)){
            return ResultGenerator.getResultByHttp(HttpStatusEnum.BAD_REQUEST);
        }
        // 设置创建时间和更新时间
        blogInfo.setCreateTime(DateUtils.getLocalCurrentDate());
        blogInfo.setUpdateTime(DateUtils.getLocalCurrentDate());
        // 注解存在更新记录，否插入一条记录
        if (blogInfoService.saveOrUpdate(blogInfo)){
            // 移除本来的标签保存新标签
            blogTagRelationService.removeAndsaveBatch(blogTagIds,blogInfo);
            return ResultGenerator.getResultByHttp(HttpStatusEnum.OKKK);
        }
        return ResultGenerator.getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR);
    }

    // 跳转到文章列表页面
    @GetMapping("/v1/blog")
    public String golist(){

        return "admin/blog-list";
    }

    // 显示数据库中的文章列表
    @GetMapping("/v1/blog/list")
    @ResponseBody
    public AjaxResultPage<BlogInfo> paging(AjaxPutPage<BlogInfo> ajaxPutPage, BlogInfo condition){

        QueryWrapper<BlogInfo> queryWrapper = new QueryWrapper<>(condition);
        queryWrapper.lambda().orderByDesc(BlogInfo::getUpdateTime);
        Page<BlogInfo> page = ajaxPutPage.putPageToPage();
        // 翻页查询
        blogInfoService.page(page,queryWrapper);
        AjaxResultPage<BlogInfo> result = new AjaxResultPage<>();
        result.setData(page.getRecords());
        result.setCount(page.getTotal());
        return result;
    }



    // 修改博客的部分状态相关信息
    @ResponseBody
    @PostMapping("/v1/blog/blogStatus")
    public Result<String> updateBlogStatus(BlogInfo blogInfo){

        // 设置更新时间
        blogInfo.setUpdateTime(DateUtils.getLocalCurrentDate());
        // 修改博客部分状态信息
        boolean flag = blogInfoService.updateById(blogInfo);
        if (flag){
            return ResultGenerator.getResultByHttp(HttpStatusEnum.OKK);
        }
        return ResultGenerator.getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR);
    }

    // 修改文章的删除状态为已删除
    @ResponseBody
    @PostMapping("/v1/blog/delete")
    public Result<String> deleteBlog(@RequestParam Long blogId){

        BlogInfo blogInfo = new BlogInfo()
                .setBlogId(blogId)
                .setIsDeleted(BlogStatusConstants.ONE)
                .setUpdateTime(DateUtils.getLocalCurrentDate());
        boolean flag = blogInfoService.updateById(blogInfo);
        if (flag){
            return ResultGenerator.getResultByHttp(HttpStatusEnum.OKK);
        }
        return ResultGenerator.getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR);
    }

    // 清除文章
    @ResponseBody
    @PostMapping("/v1/blog/clear")
    public Result<String> clearBlog(@RequestParam Long blogId){

        if (blogInfoService.clearBlogInfo(blogId)){
            return ResultGenerator.getResultByHttp(HttpStatusEnum.OKK);
        }
        return ResultGenerator.getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR);
    }

    // 把设置为已删除的文章还原
    @ResponseBody
    @PostMapping("/v1/blog/restore")
    public Result<String> restoreBlog(@RequestParam Long blogId){

        BlogInfo blogInfo = new BlogInfo()
                .setBlogId(blogId)
                .setIsDeleted(BlogStatusConstants.ZERO)
                .setUpdateTime(DateUtils.getLocalCurrentDate());
        boolean flag = blogInfoService.updateById(blogInfo);
        if (flag){
            return ResultGenerator.getResultByHttp(HttpStatusEnum.OKK);
        }
        return ResultGenerator.getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR);
    }

    @ResponseBody
    @GetMapping("v1/blog/select")
    public List<BlogInfo> getBlogInfoSelect(){
        return blogInfoService.list();
    }

}

